package com.qf.interceptor;

import com.qf.utils.APICounts;
import com.qf.vo.ApiTimeCostVo;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 统计接口的访问时长
 *
 */
@Component
public class TimeInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 记录起始时间
        long start = System.currentTimeMillis();
        // 把 start放入请求对象中，目的是在后面的postHandle可以取出

        request.setAttribute("startTime",start);
        return true;  // 放行请求
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

        long start = (long) request.getAttribute("startTime");

        // 记录终止时间
        long end = System.currentTimeMillis();

        long timecost = end - start;

        ApiTimeCostVo apiTimeCostVo = new ApiTimeCostVo(request.getRequestURI(), timecost);

        APICounts.apiTimeList.add(apiTimeCostVo);

    }
}
